/*
moxl - Modular XML Library
Copyright (c) 2007, Malcolm Sparks

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package moxl.xpath.axes;

import java.util.Iterator;

import moxl.dom.MoxlNode;
import moxl.xpath.parser.types.NodeTestMatcher;

public class XmlNodeListIterator implements Iterator<MoxlNode>
{
	private final Iterator<? extends MoxlNode> delegate;
	private final NodeTestMatcher nodeTestMatcher;
	private MoxlNode nextNode;
	private boolean exhausted;

	public XmlNodeListIterator(Iterator<? extends MoxlNode> delegate, NodeTestMatcher nodeTestMatcher)
	{
		this.delegate = delegate;
		this.nodeTestMatcher = nodeTestMatcher;
	}

	public MoxlNode next()
	{
		if (nextNode == null)
        {
			if (exhausted)
			{
				return null;
			}
			else
			{
				throw new IllegalStateException("Should call hasMoreNodes.");
			}
		}
        else
        {
			MoxlNode res = nextNode;
			nextNode = null;
			return res;
		}
	}

	public boolean hasNext()
	{
		while (delegate.hasNext())
		{
			MoxlNode next = (MoxlNode) delegate.next();
			if (nodeTestMatcher.matches(next))
			{
				nextNode = next;
				return true;
			}
		}
		exhausted = true;
		return false;
	}

	public void remove()
	{
		throw new UnsupportedOperationException("TODO");
	}

}
